import {Component, ElementRef, Renderer, Output, EventEmitter, OnInit } from '@angular/core';
import config from '../../common/utils/baseUrl';
import getData_ajax from '../../common/utils/getData_ajax';
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import * as addDays from 'date-fns/add_days';
import * as getISOWeek from 'date-fns/get_iso_week';
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh'; registerLocaleData(zh);
import * as $ from 'jquery';
import * as wangEditor from '../../../../node_modules/wangeditor/release/wangEditor.js'
import {ActivatedRoute, Router} from '@angular/router';
import {DatePipe} from '@angular/common';
import {NzModalService} from 'ng-zorro-antd';

@Component({
  selector: 'app-edit-article',
  templateUrl: './edit-article.component.html',
  styleUrls: ['./edit-article.component.scss']
})
export class EditArticleComponent implements OnInit {
  validateForm: FormGroup;

  public isSpinning:any = true; // 加载状态
  public ariticeData:any = []; // 文章数据
  public date:any = null; // 初始化日期
  public sendImgdata:any = {}; // 上传的图片数据
  public sendData:any = {
    title:'',
    img:'',
    date:'',
    details:'',
    aritice_introduction:'',
    id:0 // 0 为新增，其他为修改
  }; // 上传到接口数据
  private editor:any;
  public queryParams:any = {}; // url参数地址
  @Output() onPostData = new EventEmitter();

  constructor(private fb: FormBuilder,private el: ElementRef,private renderer: Renderer,
              private activatedRoute:ActivatedRoute, private datePipe: DatePipe,private modalService: NzModalService,
              private router: Router) { }


  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(params=> {
      this.queryParams = params;
    })
    this.validateForm = this.fb.group({
      title            : [ null, [ Validators.required ] ],
      date         : [ null, [ Validators.required ] ],
      show_img    : [ null],
      introduce      : [ null, [ Validators.required ] ]
    });
    this.getData();
  }


  // 配置wangeditor
  ngAfterViewInit() {
    let editordom = this.el.nativeElement.querySelector('#editorElem')
    // 配置服务器端地址
    this.editor = new wangEditor(editordom)
    // 配置editor图片上传路径
    this.editor.customConfig.uploadImgServer = config.baseUrl+'/inputService/uploadImg';
    // 配置editor图片上传文件名
    this.editor.customConfig.uploadFileName = 'myfile';
    this.editor.customConfig.uploadImgShowBase64 = true
    this.editor.create()
  }
  clickHandle():any {
    let data = this.editor.txt.text();//只有wangeditor的文字
    // let data = this.editor.txt.html();//只有wangeditor的包含标签的内容
    return data
  }

  // 日期改变时间
  changeDate(result: Date): void {
    console.log('onChange: ', result);
  }


  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  }

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  // 拉取数据
  getData(){
    let that = this;
    console.log(this.queryParams)
    getData_ajax.getFunc(config.baseUrl+'/articleService/getArticeData','post',this.queryParams,function(data){
        that.ariticeData = data;
        that.isSpinning = false;
        that.sendData.id = that.queryParams.id;
        // 为form表单赋值
        if(that.queryParams.id != 0){
          that.validateForm.patchValue({
            title:that.ariticeData.result[0].title,
            date:that.ariticeData.result[0].date,
            introduce:that.ariticeData.result[0].details
          });
          that.sendData.img = that.ariticeData.result[0].img;
          that.editor.txt.html(that.ariticeData.result[0].aritice_introduction);
        }
        console.log(that.ariticeData)
      },
      function(error){
        console.log(error)
      })
  }

    /**
     * 提交表单认证资料
     */
    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    verifyForm() {
        return (this.getFormControl('companyName').errors != null || this.getFormControl('legalPerson').errors != null
            || this.getFormControl('companyTel').errors != null || this.getFormControl('dutyParagraph').errors != null
            || this.getFormControl('address').errors != null || this.getFormControl('receivableBankBranch').errors != null
            || this.getFormControl('receivableCardNum').errors != null || this.getFormControl('receivableBank').errors != null);
    }

    /**
     * 提交表单
     */
  submitForm(): void {
    let that = this;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
        if(this.validateForm.controls[i].errors != null){
            return
        }
    }
    if(this.editor.txt.html() == '' || this.editor.txt.html() == null){
        this.modalService.info({
            nzTitle: '失败',
            nzContent: '提交失败，请填写文章详情再提交...'
        });
        return
    }
    // 组合数据
    this.sendData.title = this.validateForm.value.title;
    this.sendData.date = this.datePipe.transform(new Date(this.validateForm.value.date), "yyyy-MM-dd HH:mm:ss");
    this.sendData.details = this.validateForm.value.introduce;
    this.sendData.aritice_introduction = this.editor.txt.html();
    // 请求接口
    getData_ajax.getFunc(config.baseUrl+'/saveService/saveArticle', 'post', that.sendData, function(data){
        that.modalService.success({
          nzTitle: '成功',
          nzContent: '正在跳转，请稍后...'
        });
        setTimeout(()=>{
          that.router.navigateByUrl("/back/dashboard/article");
        }, 2000)
        console.log(data)
      },
      function(error){
        that.modalService.success({
          nzTitle: '失败',
          nzContent: '失败，请稍后重试...'
        });
        console.log(error)
      })
  }

  // 图片上传
  uploadImg(){
    return  $("#show_img").click();
  }
  // 图片input改变事件
  imgChange(){
    // //传标题图片到后台处理
    let titleImg=$("#show_img")[0]; //因为得到的是一个jquery类型，所以需要转化为js类型
    let titleImgFile=titleImg.files;  //获取上一步获取的titlefile对象里面的files属性名
    for(let i=0;i<titleImgFile.length;i++){
      this.sendImg(titleImgFile[i]);  //执行上面的titleImgFile
    }
  }
  sendImg(file){
    let that = this;
    this.sendImgdata=new FormData();  //动态创建form表单的一个ectype属性
    this.sendImgdata.append("myfile",file);
    getData_ajax.uploadImg(config.baseUrl+'/inputService/uploadImg', that.sendImgdata, function(data){
            console.log(data)
            that.sendData.img = data.data[0];
        },
        function(error){
            console.log(error)
        })
  }

    /**
     * 新增文章
     */
    newAriticleFunc(){
        this.router.navigateByUrl('/back/dashboard/edit-article?id=0');
        this.validateForm.reset();
    }
}
